// 性能监控工具
class PerformanceMonitor {
  constructor() {
    this.metrics = {
      pageLoadTime: 0,
      imageLoadTimes: [],
      lazyLoadCount: 0,
      totalImages: 0
    };
    this.startTime = performance.now();
  }

  // 开始监控页面加载
  startPageLoadMonitoring() {
    this.startTime = performance.now();
    
    // 监控DOM加载完成
    document.addEventListener('DOMContentLoaded', () => {
      this.metrics.pageLoadTime = performance.now() - this.startTime;
      console.log(`页面DOM加载完成，耗时: ${this.metrics.pageLoadTime.toFixed(2)}ms`);
    });

    // 监控所有资源加载完成
    window.addEventListener('load', () => {
      const totalLoadTime = performance.now() - this.startTime;
      console.log(`页面完全加载完成，总耗时: ${totalLoadTime.toFixed(2)}ms`);
      this.logPerformanceSummary();
    });
  }

  // 监控图片加载
  monitorImageLoading() {
    const images = document.querySelectorAll('img');
    this.metrics.totalImages = images.length;
    
    images.forEach((img, index) => {
      const imgStartTime = performance.now();
      
      img.addEventListener('load', () => {
        const loadTime = performance.now() - imgStartTime;
        this.metrics.imageLoadTimes.push({
          src: img.src,
          loadTime: loadTime,
          index: index
        });
        
        if (img.classList.contains('lazy-image')) {
          this.metrics.lazyLoadCount++;
        }
        
        console.log(`图片加载完成: ${img.src}, 耗时: ${loadTime.toFixed(2)}ms`);
      });

      img.addEventListener('error', () => {
        console.warn(`图片加载失败: ${img.src}`);
      });
    });
  }

  // 监控懒加载性能
  monitorLazyLoading() {
    const lazyImages = document.querySelectorAll('.lazy-image');
    let loadedCount = 0;
    
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          const img = entry.target;
          const loadStartTime = performance.now();
          
          img.addEventListener('load', () => {
            const loadTime = performance.now() - loadStartTime;
            loadedCount++;
            
            console.log(`懒加载图片完成: ${img.src}, 耗时: ${loadTime.toFixed(2)}ms, 已加载: ${loadedCount}/${lazyImages.length}`);
          });
        }
      });
    });

    lazyImages.forEach(img => observer.observe(img));
  }

  // 输出性能摘要
  logPerformanceSummary() {
    const avgImageLoadTime = this.metrics.imageLoadTimes.length > 0 
      ? this.metrics.imageLoadTimes.reduce((sum, img) => sum + img.loadTime, 0) / this.metrics.imageLoadTimes.length
      : 0;

    console.log('=== 性能监控摘要 ===');
    console.log(`页面加载时间: ${this.metrics.pageLoadTime.toFixed(2)}ms`);
    console.log(`总图片数量: ${this.metrics.totalImages}`);
    console.log(`懒加载图片数量: ${this.metrics.lazyLoadCount}`);
    console.log(`平均图片加载时间: ${avgImageLoadTime.toFixed(2)}ms`);
    console.log(`图片加载成功率: ${((this.metrics.imageLoadTimes.length / this.metrics.totalImages) * 100).toFixed(1)}%`);
  }

  // 获取内存使用情况
  getMemoryUsage() {
    if ('memory' in performance) {
      const memory = performance.memory;
      console.log('=== 内存使用情况 ===');
      console.log(`已用堆内存: ${(memory.usedJSHeapSize / 1024 / 1024).toFixed(2)}MB`);
      console.log(`总堆内存: ${(memory.totalJSHeapSize / 1024 / 1024).toFixed(2)}MB`);
      console.log(`堆内存限制: ${(memory.jsHeapSizeLimit / 1024 / 1024).toFixed(2)}MB`);
    }
  }

  // 监控分页性能
  monitorPagination() {
    const paginationButtons = document.querySelectorAll('.pagination-btn');
    
    paginationButtons.forEach(btn => {
      btn.addEventListener('click', () => {
        const clickTime = performance.now();
        
        // 监听DOM变化
        const observer = new MutationObserver(() => {
          const renderTime = performance.now() - clickTime;
          console.log(`分页切换完成，渲染耗时: ${renderTime.toFixed(2)}ms`);
          observer.disconnect();
        });
        
        observer.observe(document.body, {
          childList: true,
          subtree: true
        });
      });
    });
  }
}

// 创建全局性能监控实例
window.performanceMonitor = new PerformanceMonitor();

// 页面加载完成后启动监控
document.addEventListener('DOMContentLoaded', () => {
  window.performanceMonitor.startPageLoadMonitoring();
  window.performanceMonitor.monitorImageLoading();
  window.performanceMonitor.monitorLazyLoading();
  window.performanceMonitor.monitorPagination();
});

// 页面完全加载后获取内存使用情况
window.addEventListener('load', () => {
  setTimeout(() => {
    window.performanceMonitor.getMemoryUsage();
  }, 1000);
}); 